// API 配置和请求封装

const API_BASE_URL =
  import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'
const API_TIMEOUT = Number(import.meta.env.VITE_API_TIMEOUT) || 10000

/**
 * 请求配置接口
 */
interface RequestConfig {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  data?: any
  headers?: Record<string, string>
  timeout?: number
}

/**
 * 基础请求函数
 * @param config 请求配置
 * @returns Promise<any>
 */
export async function request<T = any>(config: RequestConfig): Promise<T> {
  const {
    url,
    method = 'GET',
    data,
    headers = {},
    timeout = API_TIMEOUT,
  } = config

  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), timeout)

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, {
      method,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: data ? JSON.stringify(data) : undefined,
      signal: controller.signal,
    })

    clearTimeout(timeoutId)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const result = await response.json()
    return result
  } catch (error) {
    clearTimeout(timeoutId)
    throw error
  }
}

/**
 * GET 请求
 * @param url 请求地址
 * @param params 查询参数
 * @returns Promise<T>
 */
export function get<T = any>(
  url: string,
  params?: Record<string, any>
): Promise<T> {
  const queryString = params ? `?${new URLSearchParams(params).toString()}` : ''
  return request<T>({ url: `${url}${queryString}`, method: 'GET' })
}

/**
 * POST 请求
 * @param url 请求地址
 * @param data 请求数据
 * @returns Promise<T>
 */
export function post<T = any>(url: string, data?: any): Promise<T> {
  return request<T>({ url, method: 'POST', data })
}

/**
 * PUT 请求
 * @param url 请求地址
 * @param data 请求数据
 * @returns Promise<T>
 */
export function put<T = any>(url: string, data?: any): Promise<T> {
  return request<T>({ url, method: 'PUT', data })
}

/**
 * DELETE 请求
 * @param url 请求地址
 * @returns Promise<T>
 */
export function del<T = any>(url: string): Promise<T> {
  return request<T>({ url, method: 'DELETE' })
}
